//
//  ZDRefreshView.swift
//  1026SwiftSinaWeiBo
//
//  Created by Apple on 15/11/3.
//  Copyright © 2015年 itcast. All rights reserved.
//

import UIKit

class ZDRefreshView: UIView {
    
    
    @IBOutlet weak var tipView: UIView!
    
    @IBOutlet weak var arrowImageView: UIImageView!
    
    @IBOutlet weak var loadingImageView: UIImageView!
    

    //MARK: - 类方法 创建refreshView
    class func refreshView() -> ZDRefreshView {
    
        return NSBundle.mainBundle().loadNibNamed("ZDRefreshView", owner: nil, options: nil).last as! ZDRefreshView
    }

    
    //MARK: - 旋转动画
    func rotationAnima(flag: Bool) {
    
        UIView.animateWithDuration(0.25, animations: { () -> Void in
            
            self.arrowImageView.transform = flag ? CGAffineTransformMakeRotation(CGFloat(M_PI)-0.01) : CGAffineTransformIdentity
        })
    }
    
    //MARK: - 开始刷新
    func startRefresh() {
        
        let animaKey = "anima"
    
        //根据指定key获取动画对象，如果能拿到，说明动画仍然在执行 直接返回 ———— 防止动画叠加
        if let _ = loadingImageView.layer.animationForKey(animaKey) {
        
            return
        }
    
        //隐藏tipView
        tipView.hidden = true
        
        //让loadingImageView旋转
        let anima = CABasicAnimation(keyPath: "transform.rotation")
        
        anima.toValue = M_PI * 2
        anima.duration = 0.25
        anima.repeatCount = MAXFLOAT
        
        //设置在控制器切换时不移除动画
        anima.removedOnCompletion = false
        
        //添加到图层中
        //addAnimation内部会根据指定key添加动画，如果key相同，则会先移除上一个动画，再添加当前添加的动画替换
        loadingImageView.layer.addAnimation(anima, forKey: animaKey)
    }
    
    //MARK: - 停止刷新
    func stopRefresh() {
    
        //显示tipView
        tipView.hidden = false
        
        //移除动画
        loadingImageView.layer.removeAllAnimations()
    }
    
    
}
